package com.wang.common.utils;

import com.wang.common.common.ErrorCode;
import com.wang.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;

/**
 * redis工具类
 */
@Slf4j
@Configuration
public class RedisUtil {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 获取value
     */
    public String get(final String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 添加key-value
     */
    public Boolean set(final String key, String value) {
        try {
            redisTemplate.opsForValue().set(key, value);
        } catch (Exception e) {
            log.error("写入缓存失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "添加缓存失败");
        }
        return true;
    }

    /**
     * 更新缓存
     */
    public Boolean getAndSet(final String key, String value) {
        try {
            redisTemplate.opsForValue().getAndSet(key, value);
        } catch (Exception e) {
            log.error("更新缓存失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新缓存失败");
        }
        return true;
    }

    /**
     * 删除缓存
     */
    public Boolean delete(final String key) {
        try {
            redisTemplate.delete(key);
        } catch (Exception e) {
            log.error("删除缓存失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "缓存删除失败");
        }
        return true;
    }

    /**
     * 获取value
     */
    public String getString(final String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    /**
     * 添加key-value
     */
    public Boolean setString(final String key, String value) {
        try {
            stringRedisTemplate.opsForValue().set(key, value);
        } catch (Exception e) {
            log.error("写入缓存失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "添加缓存失败");
        }
        return true;
    }

    /**
     * 更新缓存
     */
    public Boolean getAndSetString(final String key, String value) {
        try {
            stringRedisTemplate.opsForValue().getAndSet(key, value);
        } catch (Exception e) {
            log.error("更新缓存失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新缓存失败");
        }
        return true;
    }

    /**
     * 删除缓存
     */
    public Boolean deleteString(final String key) {
        try {
            stringRedisTemplate.delete(key);
        } catch (Exception e) {
            log.error("删除缓存失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "缓存删除失败");
        }
        return true;
    }
}
